<?php
/**
 * Created by PhpStorm.
 * User: lts
 * Date: 2018/4/25
 * Time: 16:17
 */

global $_GPC, $_W;

$GLOBALS['frames'] = $this->getMainMenu();

$branch_list = pdo_getall('yzzc_sun_branch', ['uniacid' => $_W['uniacid']], ['id', 'name']);
$distribution_list = pdo_getall('yzzc_sun_distribution_promoter', ['uniacid' => $_W['uniacid'], 'status' => 1], ['uid', 'name']);
$shuttle_list = pdo_getall('yzzc_sun_shuttle', ['uniacid' => $_W['uniacid']], ['id', 'name']);

$where = "uniacid =" . $_W['uniacid'];
if ($_GPC['keywords']) {
    $keywords = $_GPC['keywords'];
    $where .= " and (ordernum LIKE  '%$keywords%' or carnum LIKE  '%$keywords%' or shuttle_name LIKE  '%$keywords%' or reclaim_shuttle_name LIKE  '%$keywords%')";
}
$status = 6;
if ($_GPC['type']) {
    $status = $_GPC['status'];

    if ($_GPC['type'] == 'all') {
        $where = "uniacid =" . $_W['uniacid'];
    } else {
        $where = "uniacid =" . $_W['uniacid'] . " and status =" . $_GPC['status'];

    }
}

if ($_GPC['istui'] != null) {

    $istui = $_GPC['istui'];
    $refund = $_GPC['refund'];
    $where .= " and  istui =" . $_GPC['istui'];

}
if ($_GPC['isdeposit'] != null) {

    $isdeposit = $_GPC['isdeposit'];
    $deposit = $_GPC['deposit'];
    $where .= " and  isdeposit =" . $_GPC['isdeposit'];

}
if ($_GPC['del'] == 'del') {
    $isdel = $_GPC['isdel'];
    $del = $_GPC['del'];
    $where .= " and display = 0";
}

$branch_id = $_GPC['branch_id'] ?? '';
if ($branch_id) {
    $where .= " and start_shop=" . $branch_id;
}

$range_time = $_GPC['range_time'] ?? [];
$start_time = $end_time = '';
if ($range_time['start'] && $range_time['end']) {
    $start_time = $range_time['start'];
    $end_time = $range_time['end'];
    $end_time = strtotime($end_time);
    $start_time = strtotime($start_time);
    $where .= ' and createtime > ' . $start_time . ' and createtime<=' . $end_time;
}

$distribution_id = $_GPC['distribution_id'] ?? '';
if ($distribution_id) {
    $where .= ' and distribution_id = ' . $distribution_id;
}

//$shuttle_id = $_GPC['shuttle_id'] ?? '';
//if ($shuttle_id) {
//    $where .= ' and shuttle_id = ' . $shuttle_id;
//}


//var_dump($where);exit;
// $where .=" and display = 1" ;
//var_dump($where);exit;
$type = $_GPC['type'] ? $_GPC['type'] : 'all';
$page = max(1, intval($_GPC['page']));
$size = intval($_GPC['psize']) ? intval($_GPC['psize']) : 10;
$sql = "SELECT * FROM ims_yzzc_sun_order where " . $where . " ORDER BY id DESC LIMIT " . (($page - 1) * $size) . ',' . $size;
//var_dump($sql);exit;
$list = pdo_fetchall($sql);
if ($list) {
    foreach ($list as $key => $value) {
        $list[$key]['createtime'] = date('Y-m-d', $value['createtime']);
        if ($value['paytime']) {
            $list[$key]['paytime'] = date('Y-m-d H:i', $value['paytime']);
        }
        $list[$key]['start_time'] = date('Y-m-d', $value['start_time']);
        if ($value['iszx'] == 1) {
            $xzorder = pdo_get('yzzc_sun_xzorder', array('uniacid' => $_W['uniacid'], 'ordernum' => $value['ordernum'], 'ispay' => 1));
            $list[$key]['end_time'] = $xzorder['end_time'];
            $list[$key]['day'] = $xzorder['day'] + $value['day'];
            $list[$key]['xzmoney'] = $xzorder['total_money'];
        }

        if ($value['end_time'] > 0) {
            $list[$key]['end_time'] = date('Y-m-d', $list[$key]['end_time']);
        } else {
            $list[$key]['end_time'] = '暂无';
        }

        if ($value['usetime']) {
            $list[$key]['usetime'] = date('Y-m-d H:i', $value['usetime']);
        }
        if ($value['return_time']) {
            $list[$key]['return_time'] = date('Y-m-d H:i', $value['return_time']);
        }
        $list[$key]['carname'] = pdo_get('yzzc_sun_goods', array('id' => $value['cid']), array('name'))['name'];
        $list[$key]['shopname'] = pdo_get('yzzc_sun_branch', array('id' => $value['start_shop']), array('name'))['name'];
        $list[$key]['nickname'] = pdo_get('yzzc_sun_user', array('id' => $value['uid']), array('user_name'))['user_name'];
        // $list[$key]['endtime']='未续租';

        // if($value['iszx']==1){
        // $xzorder = pdo_get('yzzc_sun_xzorder',array('uniacid'=>$_W['uniacid'],'ordernum'=>$value['ordernum']));
        // $list[$key]['xztime']=date('Y-m-d H:i:s',$value['xztime']);
        // $list[$key]['xzmoney']=date('Y-m-d H:i:s',$xzorder['end_time']);
        // }

    }
    $total = pdo_fetchcolumn("select count(*) from ims_yzzc_sun_order where " . $where);
    $pager = pagination($total, $page, $size);
}


if ($_GPC['op'] == 'delete') {
    $order = pdo_get('yzzc_sun_order', array('id' => $_GPC['oid']), array('status'));
//    var_dump($_GPC['oid']);exit;
    // if($order['status']<3){
    //     message('该订单还未完成不可删除','','error');
    // }
    $res = pdo_update('yzzc_sun_order', array('display' => 0, 'status' => 7), array('id' => $_GPC['oid']));
    if ($res) {
        message('删除成功！', $this->createWebUrl('order'), 'success');
    } else {
        message('删除失败！', '', 'error');
    }
}
/*还车*/
if ($_GPC['op'] == 'cancel') {
    $order = pdo_get('yzzc_sun_order', array('id' => $_GPC['id']));
    if ($order['status'] == 1) {
        $res = pdo_update('yzzc_sun_order', array('status' => 4), array('id' => $_GPC['id'], 'uniacid' => $_W['uniacid']));
        if ($res) {
            // pdo_update('yzzc_sun_goods',array('status'=>1),array('id'=>$order['cid'],'uniacid'=>$_W['uniacid']));
            message('取消成功！', $this->createWebUrl('order'), 'success');
        } else {
            message('取消失败！', '', 'error');
        }
    } else {
        message('当前车辆无法取消！', '', 'error');
    }

}
if ($_GPC['op'] == 'update') {
    $order = pdo_get('yzzc_sun_order', array('id' => $_GPC['id'], 'uniacid' => $_W['uniacid']));
    if ($order['status'] != 0) {
        $res = pdo_update('yzzc_sun_order', array('prepay_money' => $_GPC['prepay_money'], 'total_money' => $_GPC['prepay_money']), array('id' => $_GPC['id'], 'uniacid' => $_W['uniacid']));
        if ($res) {
            //创建分销收益
            include_once IA_ROOT . "/addons/" . $_W["current_module"]["name"] . "/inc/func/distribution.php";
            $distribution = new Distribution();
            $distribution->order_id = $_GPC['id'];
            $distribution->money = $_GPC['prepay_money'];
            $distribution->usertype = 1;
            $distribution->userid = 0;
            $distribution->parent_id = $order['distribution_id'];
            $distribution->ordertype = 1;
            $distribution->computecommission();
            // pdo_update('yzzc_sun_goods',array('status'=>1),array('id'=>$order['cid'],'uniacid'=>$_W['uniacid']));
            message('修改成功！', $this->createWebUrl('order'), 'success');
        } else {
            message('修改失败！', '', 'error');
        }
    } else {
        message('当前订单无法修改！', '', 'error');
    }
}
if ($_GPC['op'] == 'update_shuttle') {
    $order = pdo_get('yzzc_sun_order', array('id' => $_GPC['id'], 'uniacid' => $_W['uniacid']));
    if ($order['total_money'] < $_GPC['shuttle_commission']) {
        message('佣金不能超过订单总额！', '', 'error');

    }
    $res = pdo_update('yzzc_sun_order', array('shuttle_commission' => $_GPC['shuttle_commission']), array('id' => $_GPC['id'], 'uniacid' => $_W['uniacid']));
    if ($res) {
        message('修改成功！', $this->createWebUrl('order'), 'success');
    } else {
        message('修改失败！', '', 'error');
    }
}
/*还车*/
if ($_GPC['op'] == 'return') {
    $order_id = $_GPC['id'] ? $_GPC['id'] : $_GPC['order_id'];
    $order = pdo_get('yzzc_sun_order', array('id' => $order_id));

    $type = $_GPC['type'];
    $order['start_time'] = date('Y-m-d', $order['start_time']);
    $order['end_time'] = date('Y-m-d', $order['end_time']);

    if (checksubmit('submit')) {

        try {
            pdo_fetchall('START TRANSACTION');//启动一个新事务
            if ($type == 1) {
                //交车
                $data = [
                    'uniacid' => $_W['uniacid'],
                    'order_id' => $order_id,
                    'shuttle_id' => $order['shuttle_id'],
                    'delivery_start_time' => strtotime(trim($_GPC['delivery_start_time'])),
                    'delivery_start_pic' => $_GPC['delivery_start_pic'] ? implode(',', $_GPC['delivery_start_pic']) : '',
                    'delivery_start_meter' => $_GPC['delivery_start_meter'] ? implode(',', $_GPC['delivery_start_meter']) : '',
                    'delivery_end_time' => strtotime(trim($_GPC['delivery_start_time'])),
                    'delivery_end_pic' => $_GPC['delivery_end_pic'] ? implode(',', $_GPC['delivery_end_pic']) : '',
                    'delivery_end_meter' => $_GPC['delivery_end_meter'] ? implode(',', $_GPC['delivery_end_meter']) : '',
                    'createtime' => time(),
                ];
                $shuttle_add = pdo_insert('yzzc_sun_shuttle_delivery', $data);
                $order_update = pdo_update('yzzc_sun_order', ['status' => 3, 'usetime' => time()], ['id' => $order_id]);
                $shuttle_update = pdo_update('yzzc_sun_shuttle_income', ['order_status' => 1], ['order_id' => $order_id, 'shuttle_id' => $order['shuttle_id']]);

                if ($shuttle_add && $order_update && $shuttle_update) {
                    pdo_fetchall('COMMIT');//事务提交
                    message('交车成功', $this->createWebUrl('order'), 'success');
                }
                pdo_fetchall('ROLLBACK');//事务回滚
                message('交车失败', $this->createWebUrl('order'), 'error');
            } elseif ($type == 2) {
                //还车
                $data = [
                    'delivery_end_time' => strtotime(trim($_GPC['time'])),
                    'delivery_end_pic' => $_GPC['delivery_end_pic'] ? implode(',', $_GPC['delivery_end_pic']) : '',
                    'delivery_end_meter' => $_GPC['delivery_end_meter'] ? implode(',', $_GPC['delivery_end_meter']) : '',
                ];

//                //创建商家结算费用
//                $branch_income = pdo_get("yzzc_sun_branch_income", ["uniacid" => $_W["uniacid"], "branch_id" => $order["start_shop"],'order_id'=>$order['id']]);
//                if ($branch_income){
//                    //存在收益。直接结算
//                    $income_result = pdo_update('yzzc_sun_branch_income',['status' => 1,'income_time' => time()],['id'=>$branch_income['id']]);
//                    if (!$income_result){
//                        pdo_fetchall('ROLLBACK');//事务提交
//                        $this->return_msg(-1, [],'结算商家收益失败');
//                    }
//                }

                $goods = pdo_get('yzzc_sun_goods', ['id' => $order['cid']]);
                if ($goods['status'] != 1) {
                    pdo_update('yzzc_sun_goods', ['status' => 1], ['id' => $order['cid']]);
                }

                pdo_update('yzzc_sun_ordertime', ['end_time' => $data['delivery_end_time'], 'status' => 0], ['sku_id' => $order['sku_id'], 'order_id' => $order['id']]);

                $delivery_update = pdo_update('yzzc_sun_shuttle_delivery', $data, ['order_id' => $order_id]);
                $order_update = pdo_update('yzzc_sun_order', ['status' => 0, 'return_time' => time()], ['id' => $order['id']]);
//                $shuttle_update = pdo_update('yzzc_sun_shuttle_income',['order_status'=>2,'status' => 1,'income_time' => time()],['order_id'=>$order['id'],'shuttle_id'=>$order['shuttle_id']]);
                if ($delivery_update && $order_update) {
                    pdo_fetchall('COMMIT');//事务提交
                    message('还车成功', $this->createWebUrl('order'), 'success');
                }
                pdo_fetchall('ROLLBACK');//事务回滚
                message('还车失败', $this->createWebUrl('order'), 'error');
            } else {
                $this->return_msg(-1, [], '类型状态错误');
            }
        } catch (Exception $exception) {
            $this->return_msg(-1, [], '类型状态错误');
        }
    }

    include $this->template('web/order_return');
    return;


//    $order = pdo_get('yzzc_sun_order', array('id' => $_GPC['id']));
//    if ($order['status'] == 3) {
//        $res = pdo_update('yzzc_sun_order', array('status' => 0, 'return_time' => time()), array('id' => $_GPC['id'], 'uniacid' => $_W['uniacid']));
//        if ($res) {
//            $res1 = pdo_delete('yzzc_sun_ordertime', array('carnum' => $order['carnum'], 'start_time' => $order['start_time'], 'uniacid' => $_W['uniacid'], 'end_time' => $order['end_time']));
//            if ($order['iszx'] == 1) {
//                $xzorder = pdo_get('yzzc_sun_xzorder', array('ordernum' => $order['ordernum'], 'uniacid' => $_W['uniacid']));
//                if ($xzorder['ispay'] == 1) {
//                    $res2 = pdo_delete('yzzc_sun_ordertime', array('carnum' => $order['carnum'], 'start_time' => $xzorder['start_time'], 'uniacid' => $_W['uniacid'], 'end_time' => $xzorder['end_time']));
//                }
//            }
//
//            //查看租赁方式
//            $zlsz = pdo_get('yzzc_sun_order_set', array('uniacid' => $_W['uniacid']), array('zlsz'));
//            if ($zlsz['zlsz'] == 0) {
//                pdo_update('yzzc_sun_goods', array('status' => 1), array('uniacid' => $_W['uniacid'], 'carnum' => $order['carnum']));
//            }
//            // pdo_update('yzzc_sun_goods',array('status'=>1),array('id'=>$order['cid'],'uniacid'=>$_W['uniacid']));
//
//            //更新分销
//            /*======分销使用====== */
//            include_once IA_ROOT . '/addons/' . $_W['current_module']['name'] . '/inc/func/distribution.php';
//            $distribution = new Distribution();
//            $distribution->order_id = $_GPC['id'];
//            //1短租 2长租
//            $distribution->ordertype = 1;
//            $distribution->settlecommission();
//            /*======分销使用======*/
//
//            message('还车成功！', $this->createWebUrl('order'), 'success');
//        } else {
//            message('还车失败！', '', 'error');
//        }
//    } else {
//        message('当前车辆无法还车！', '', 'error');
//    }

}
if ($_GPC['op'] == 'refund') {
    $id = intval($_GPC['id']);
    $uniacid = $_W['uniacid'];
    $refund = intval($_GPC['refund']);
    if ($refund == 3) {
        $ress = pdo_update('yzzc_sun_order', array("istui" => 3), array('id' => $id, 'uniacid' => $uniacid));
        if ($ress) {
            message('拒绝成功！', $this->createWebUrl('order'), 'success');
        } else {
            message('拒绝失败！', '', 'error');
        }
    }

    $tuimoney = pdo_get('yzzc_sun_order_set', array('uniacid' => $_W['uniacid']), array('tuimoney'))['tuimoney'];
    if ($tuimoney) {
        $tuimoney = $tuimoney / 100;
    } else {
        $tuimoney = 1;
    }
    // var_dump($tuimoney);
    // //获取订单信息
    $order = pdo_get('yzzc_sun_order', array('uniacid' => $uniacid, 'id' => $id), array('ordernum', "prepay_money", 'deposit_money', "out_trade_no", "out_refund_no", "cid", 'uid', 'carnum', 'start_time', 'end_time'));

    // $price= $order['prepay_money'] * 100 * $tuimoney ; 
    $Total_fee = ($order['prepay_money'] + $order['deposit_money']) * 100;
    $Refund_fee = $order['prepay_money'] * $tuimoney * 100;
    if ($Refund_fee < 1) {
        $Refund_fee = 1;
    }
    // var_dump($Total_fee);
    // var_dump($tuimoney);
    // var_dump($Refund_fee);
    //退款操作
    include_once IA_ROOT . '/addons/yzzc_sun/cert/WxPay.Api.php';
    load()->model('account');
    load()->func('communication');
    //获取appid和appkey
    $res = pdo_get('yzzc_sun_system', array('uniacid' => $uniacid));
    $appid = $res['appid'];
    $wxkey = $res['wxkey'];
    $mchid = $res['mchid'];
    $path_cert = IA_ROOT . '/addons/yzzc_sun/cert/' . $res['apiclient_cert'];
    $path_key = IA_ROOT . '/addons/yzzc_sun/cert/' . $res['apiclient_key'];
    $out_trade_no = $order['out_trade_no'];
    // $fee = $price;
    $out_refund_no = $order['out_refund_no'] ? $order['out_trade_no'] : $mchid . rand(100, 999) . time() . rand(1000, 9999);
    $WxPayApi = new WxPayApi();
    $input = new WxPayRefund();
    $input->SetAppid($appid);
    $input->SetMch_id($mchid);
    $input->SetOp_user_id($mchid);
    $input->SetRefund_fee($Refund_fee);
    $input->SetTotal_fee($Total_fee);
    $input->SetOut_refund_no($out_refund_no);
    $input->SetOut_trade_no($out_trade_no);
    $result = $WxPayApi->refund($input, 6, $path_cert, $path_key, $wxkey);
    // var_dump($result);
    // die;
    if ($result['result_code'] == 'SUCCESS') {
        //退款成功
        pdo_delete('yzzc_sun_ordertime', array('carnum' => $order['carnum'], 'start_time' => $order['start_time'], 'uniacid' => $_W['uniacid'], 'end_time' => $order['end_time']));

        pdo_update('yzzc_sun_order', array("istui" => 2, 'status' => 5, "out_refund_no " => $out_refund_no), array('id' => $id, 'uniacid' => $uniacid));

        //查看租赁方式
        $zlsz = pdo_get('yzzc_sun_order_set', array('uniacid' => $_W['uniacid']), array('zlsz'));
        if ($zlsz['zlsz'] == 0) {
            pdo_update('yzzc_sun_goods', array('status' => 1), array('uniacid' => $_W['uniacid'], 'carnum' => $order['carnum']));
        }
        message('退款成功！', $this->createWebUrl('order'), 'success');
    } else {
        pdo_update('yzzc_sun_order', array("istui " => 3, "out_refund_no " => $out_refund_no), array('id' => $id, 'uniacid' => $uniacid));

        message('退款失败！微信' . $result["err_code_des"], '', 'error');

    }
}
if ($_GPC['op'] == 'refunddeposit') {
    $id = intval($_GPC['id']);
    $uniacid = $_W['uniacid'];
    $refund = intval($_GPC['refund']);
    if ($refund == 3) {
        $ress = pdo_update('yzzc_sun_order', array("isdeposit" => 3), array('id' => $id, 'uniacid' => $uniacid));
        if ($ress) {
            message('拒绝成功！', $this->createWebUrl('order'), 'success');
        } else {
            message('拒绝失败！', '', 'error');
        }
    }
    $order_set = pdo_get('yzzc_sun_order_set', array('uniacid' => $_W['uniacid']), array('tuimoney', 'depositway'));
    // if($order_set){
    //     $tuimoney=$order_set['tuimoney']/100;
    // }else{
    //     $tuimoney=1;
    // }
    if ($order_set['depositway'] == 1) {
        //获取订单信息
        $order = pdo_get('yzzc_sun_order', array('uniacid' => $uniacid, 'id' => $id), array('ordernum', "deposit_money", 'prepay_money', "out_trade_no", "out_refund_no"));


        if ($_GPC['deposit_money'] <= 0) {
            //如果小于0 不退款，直接修改状态
            pdo_update('yzzc_sun_order', ["isdeposit " => 2, "out_refund_no " => '', 'deposit_money' => $_GPC['deposit_money']], array('id' => $id, 'uniacid' => $uniacid));
            message('退押金成功！', $this->createWebUrl('order'), 'success');
        }

        $total_fee = $order['deposit_money'] + $order['prepay_money'];
        $refund_fee = $order['deposit_money'];
        if ($_GPC['deposit_money'] > $total_fee) {
            message('退押金金额不能大于总订单金额', '', 'error');
        }

        if ($_GPC['deposit_money'] != $order['deposit_money']) {
            //退款金额不和押金相等，用设置的退款
            $total_fee = $_GPC['deposit_money'] + $order['prepay_money'];
            $refund_fee = $_GPC['deposit_money'];
        }

        $total_fee = $total_fee * 100;
        $refund_fee = $refund_fee * 100;

        include_once IA_ROOT . '/addons/yzzc_sun/cert/WxPay.Api.php';
        load()->model('account');
        load()->func('communication');

        //获取appid和appkey
        $res = pdo_get('yzzc_sun_system', array('uniacid' => $uniacid));

        $appid = $res['appid'];
        $wxkey = $res['wxkey'];
        $mchid = $res['mchid'];

        $path_cert = IA_ROOT . "/attachment/" . $res['apiclient_cert'];
        $path_key = IA_ROOT . "/attachment/" . $res['apiclient_key'];
        $out_trade_no = $order['out_trade_no'];

        $out_refund_no = $order['out_refund_no'] ? $order['out_trade_no'] : $mchid . rand(100, 999) . time() . rand(1000, 9999);

        $WxPayApi = new WxPayApi();
        $input = new WxPayRefund();

        $input->SetAppid($appid);
        $input->SetMch_id($mchid);
        $input->SetOp_user_id($mchid);
        $input->SetRefund_fee($refund_fee);
        $input->SetTotal_fee($total_fee);
        $input->SetOut_refund_no($out_refund_no);
        $input->SetOut_trade_no($out_trade_no);
        $result = $WxPayApi->refund($input, 6, $path_cert, $path_key, $wxkey);

        if ($result['result_code'] == 'SUCCESS') {
            //退款成功
            pdo_update('yzzc_sun_order', array(
                "isdeposit " => 2,
                "out_refund_no " => $out_refund_no,
                'deposit_money' => $_GPC['deposit_money']
            ), array('id' => $id, 'uniacid' => $uniacid));
            message('退押金成功！', $this->createWebUrl('order'), 'success');

        } else {
            pdo_update('yzzc_sun_order', array(
                "isdeposit " => 3,
                "out_refund_no " => $out_refund_no,
                'deposit_money' => $_GPC['deposit_money']), array('id' => $id, 'uniacid' => $uniacid)
            );
            message('退押金失败！微信' . $result["err_code_des"], '', 'error');
        }
    } else {
        pdo_update('yzzc_sun_order', array(
            "isdeposit " => 2,
            "out_refund_no " => $out_refund_no,
            'deposit_money' => $_GPC['deposit_money']
        ), array('id' => $id, 'uniacid' => $uniacid));
        message('退押金成功！', $this->createWebUrl('order'), 'success');
    }

}
//导出
if ($_GPC['op'] == 'exportorder') {
    $where = ' where uniacid = ' . $_W['uniacid'] . ' and display = 1';
    if ($_GPC['status'] != 6 && $_GPC['status']) {
        $where .= " and status = " . $_GPC['status'];
    }
    $sql = "SELECT * FROM ims_yzzc_sun_order " . $where . " ORDER BY id DESC";
    // var_dump($sql);die;
    $orderlist = pdo_fetchall($sql);
    // $select_sql =$sql." order by a.order_id desc,a.id asc ";
    // $orderlist=pdo_fetchall($select_sql,$data);
    $export_title_str = "订单号,订单类型,门店名称（门店id）,车辆名称（车辆id）（车牌号）,租车开始时间,租车结束时间,天数,微信名（用户id）,定金,下单时间,付款时间,单价 / 手续费 / 基础服务费,积分抵现 / 优惠券抵现,是否选择尊享服务（价钱）,取车方式,取车名称/手机,取车时间,还车时间,订单状态";
    $export_title = explode(',', $export_title_str);
    $export_list = array();
    $status = array("已完成", "待支付", "已支付", "已取车", "已取消", "已退款");
    $refund = array("否", "退款申请中", "已退款", "拒绝退款");
    $i = 1;
    foreach ($orderlist as $k => $v) {

        $export_list[$k]["ordernum"] = $v["ordernum"] . "\t";
        $export_list[$k]["type"] = $v["type"] == 1 ? '短租订单' . "\t" : '长租订单' . "\t";
        $export_list[$k]["shopname"] = pdo_get('yzzc_sun_branch', array('id' => $v['start_shop']), array('name'))['name'] . "(" . $v['start_shop'] . ")" . "\t";
        $export_list[$k]["carname"] = pdo_get('yzzc_sun_goods', array('id' => $v['cid']), array('name'))['name'] . "(" . $v['cid'] . ")" . "(" . $v['carnum'] . ")" . "\t";
        $export_list[$k]["start_time"] = date("Y-m-d H:i:s", $v["start_time"]) . "\t";
        $export_list[$k]["end_time"] = date("Y-m-d H:i:s", $v["end_time"]) . "\t";
        $export_list[$k]["day"] = $v["day"] . "\t";
        $export_list[$k]["nickname"] = pdo_get('yzzc_sun_user', array('id' => $v['uid']), array('user_name'))['user_name'] . "\t";
        $export_list[$k]["prepay_money"] = $v["prepay_money"];
        $export_list[$k]["createtime"] = date("Y-m-d H:i:s", $v["createtime"]) . "\t";
        $export_list[$k]["paytime"] = $v["paytime"] ? date("Y-m-d H:i:s", $v["paytime"]) . "\t" : " ";
        $export_list[$k]["money"] = "￥" . $v['money'] . "/ ￥" . $v['fee'] . "/ ￥" . $v['service_fee'];
        $export_list[$k]["integral"] = $v['integral'] . "积分抵￥" . $v['integral_money'] . "/ ￥" . $v['coupon_money'];
        $export_list[$k]["zx"] = $v["open_zx_service"] == 1 ? "开启（￥" . $v['zx_service_fee'] . "）" : "关闭";
        $export_list[$k]["gettype"] = $v["gettype"] == 1 ? "到店自取" : "送车上门";
        $export_list[$k]["name"] = $v['username'] . "/ " . $v['tel'];
        $export_list[$k]["usetime"] = $v["usetime"] ? date("Y-m-d H:i:s", $v["usetime"]) . "\t" : " ";
        $export_list[$k]["return_time"] = $v["return_time"] ? date("Y-m-d H:i:s", $v["return_time"]) . "\t" : " ";

        $export_list[$k]["status"] = $status[$v["status"]];

        $i++;
    }
    $exporttitle = "租车订单";
    exportToExcel($exporttitle . '_' . date("YmdHis") . '.csv', $export_title, $export_list);
    exit;
}

if ($_GPC['op'] == 'booking') {
    if (checksubmit('submit')) {
        $is_inner1 = $_GPC['is_inner'];
        $exterior_number = $_GPC['exterior_number'];
        $name = $_GPC['name'];
        $mobile = $_GPC['mobile'];
        $start_time = strtotime($_GPC['start_time']);
        $end_time = strtotime($_GPC['end_time']);
        $money = $_GPC['money'];
        $fee = $_GPC['fee'];
        $deposit_money = $_GPC['deposit_money'];
        $start_shop = $_GPC['start_shop'];
        if ($start_time >= $end_time) {
            message('开始时间不能大于结束时间！', '', 'error');
        }

        if ($is_inner1 == 2 && empty($exterior_number)) {
            message('外调车型请输入车牌号！', '', 'error');
        }

        if ($is_inner1 == 2 && empty($start_shop)) {
            message('外调车型请选择发车门店！', '', 'error');
        }
        if (!$name || !$mobile) {
            message('请输入客户姓名电话！', '', 'error');
        }

        $cle = $end_time - $start_time; //得出时间戳差值
        $day = floor($cle / 3600 / 24);
        $hour = floor(($cle % (3600 * 24)) / 3600);  //%取余
        if ($hour >= 4) {
            //大于4小时算一天
            $day += 1;
        } elseif ($hour < 4 && $hour > 0) {
            //小于4小时 但是大于0 算半天
            $day += 0.5;
        }
        $cid = 0;

        $car_num = $exterior_number;

        $data = [
            'uniacid' => $_W['uniacid'],
            'is_inner' => $is_inner1,
            'cid' => $cid,
//            'sku_id' => $sku_id,
            'uid' => 0,
            'carnum' => $car_num,
            'type' => 1,
            'day' => $day,
            'createtime' => time(),
            'username' => $name,
            'tel' => $mobile,
            'ordernum' => date("YmdHis") . str_pad(mt_rand(1, 9999), 4, "0", STR_PAD_LEFT),
//            'start_shop' => $start_shop,
//            'end_shop' => $end_shop,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'source_type' => 2,
            'status' => 2,
            'deposit_money' => $deposit_money,
            'fee' => $fee,
            'money' => $money,
            'total_money' => $money + $fee,
            'prepay_money' => $money + $fee,
            'gettype' => $_GPC['gettype'],
            'car_name' => trim($_GPC['car_name']),
            'pay_type' => 2 //线下收款
        ];

        $store_income = [];
        if ($is_inner1 == 1) {
            $sku_id = $_GPC['sku_id'];
            $sku = pdo_get('yzzc_sun_goods_sku', ['id' => $sku_id]);
            $goods = pdo_get('yzzc_sun_goods', ['id' => $sku['goods_id']]);
            $cid = $sku['goods_id'];
            $sku_id = $_GPC['sku_id'];
            $car_num = $sku['carnum'];
            //门店
            $start_shop = $end_shop = $goods['sid'];

            $data['car_name'] = $sku['name'];
            //是否是个人车主车辆
            if ($goods['store_id'] > 0) {
                $store_info = $goods = pdo_get('yzzc_sun_store', ['store_id' => $sku['store_id']]);
                if (!$store_info) {
                    pdo_fetchall('ROLLBACK');//事务回滚
                    message('预订失败', $this->createWebUrl('order', array()), 'error');
                }
                //创建收益
                $platform_fee = round($data['prepay_money'] * ($store_info['platform_fee'] / 100), 2);
                $store_income = [
                    'type' => 3,
                    'branch_id' => 0,
                    'uniacid' => $store_info['uniacid'],
                    'total' => $data['prepay_money'],
                    'platform_fee' => $platform_fee,
                    'amount' => $data['prepay_money'] - $platform_fee,
                    'createtime' => time(),
                ];
            }
        } else {
            $start_shop = $end_shop = $_GPC['start_shop'];
            $sku_id = 0;
        }

        $data['sku_id'] = $sku_id;
        $data['start_shop'] = $start_shop;
        $data['end_shop'] = $start_shop;
        //检测是否存在重复预订
        isOrder($sku_id, $car_num, $end_time, $start_time);
        try {
            pdo_fetchall('START TRANSACTION');//启动一个新事务

            $zlsz = pdo_get("yzzc_sun_order_set", ["uniacid" => $_W["uniacid"]], ["zlsz", 'shuttle_type', 'shuttle_commission']);
            //计算交还车原收益
            $shuttle_commission = 0;
            if ($zlsz['shuttle_type'] == 1) {
                //订单总额百分比
                $shuttle_commission = round(($zlsz['shuttle_commission'] / 100) * $data['prepay_money'], 2);
            }
            if ($zlsz['shuttle_type'] == 2) {
                //订单总额固定值
                $shuttle_commission = $zlsz['shuttle_commission'];
            }
            $data['shuttle_commission'] = $shuttle_commission;

            pdo_insert('yzzc_sun_order', $data);
            $order_id = pdo_insertid();
            if (!$order_id) {
                pdo_fetchall('ROLLBACK');//事务回滚
                message('预订失败', $this->createWebUrl('order', array()), 'error');
            }

            //更新订单时间
            $data1 = [
                'start_time' => $start_time,
                'end_time' => $end_time,
                'carnum' => $car_num,
                'order_id' => $order_id,
                'goods_id' => $cid,
                'sku_id' => $sku_id,
                'uniacid' => $_W["uniacid"],
            ];
            $order_time = pdo_insert("yzzc_sun_ordertime", $data1);
            if (!$order_time) {
                pdo_fetchall('ROLLBACK');//事务回滚
                message('预订失败', $this->createWebUrl('order', array()), 'error');
            }

            $branch = pdo_get("yzzc_sun_branch", ["uniacid" => $_W["uniacid"], "id" => $start_shop]);
            //创建收益
            $platform_fee = round($data['prepay_money'] * ($branch['platform_fee'] / 100), 2);
            $income = [
                'type' => $branch['type'],
                'branch_id' => $branch['id'],
                'uniacid' => $branch['uniacid'],
                'order_id' => $order_id,
                'total' => $data['prepay_money'],
                'platform_fee' => $platform_fee,
                'amount' => $data['prepay_money'] - $platform_fee,
                'createtime' => time(),
            ];

            if ($store_income) {
                //创建个人车主收益
                $store_income['order_id'] = $order_id;
                $store_income_result = pdo_insert('yzzc_sun_branch_income', $store_income);
                if (!$store_income_result) {
                    pdo_fetchall('ROLLBACK');//事务回滚
                    message('创建订单收益失败', $this->createWebUrl('order', array()), 'error');
                }
            }

            $branch_income = pdo_insert('yzzc_sun_branch_income', $income);

            if (!$branch_income) {
                pdo_fetchall('ROLLBACK');//事务回滚
                message('创建订单收益失败', $this->createWebUrl('order', array()), 'error');
            }

            pdo_fetchall('COMMIT');//事务提交
            message('预订成功', $this->createWebUrl('order', array()), 'success');
        } catch (Exception $exception) {
            pdo_fetchall('ROLLBACK');//事务回滚
            message('预订失败', '', 'error');
        }
    }
    $sku = pdo_getall('yzzc_sun_goods_sku', ['is_del' => 0]);
    $store_list = pdo_getall('yzzc_sun_branch');
    include $this->template('web/order_booking');
    return;
}
if ($_GPC['op'] == 'fees') {
    $order = pdo_get('yzzc_sun_order', ['id' => $_GPC['id']]);
    $order['start_time'] = date('Y-m-d', $order['start_time']);
    $order['end_time'] = date('Y-m-d', $order['end_time']);
    $order_id = $_GPC['id'];
    $order['distribution_name'] = '';
    $delivery = pdo_get('yzzc_sun_shuttle_delivery', ['order_id' => $order_id]);
    $delivery['delivery_start_meter'] = $delivery['delivery_start_meter'] ? explode(",", $delivery['delivery_start_meter']) : [];
    $delivery['delivery_end_meter'] = $delivery['delivery_end_meter'] ? explode(",", $delivery['delivery_end_meter']) : [];
    if ($order['distribution_id']) {
        $order['distribution_name'] = pdo_fetchcolumn('select name from ' . tablename('yzzc_sun_distribution_promoter') . ' where uid = :id', ['id' => $order['distribution_id']]);
    }

//    if ($order['shuttle_id']){
//        $order['shuttle_name'] = pdo_fetchcolumn('select name from '.tablename('yzzc_sun_shuttle').' where id = :id', ['id' => $order['shuttle_id']]);
//    }

    if (checksubmit('submit')) {
        $branch_name = pdo_fetchcolumn('select name from ' . tablename('yzzc_sun_branch') . ' where id = :start_shop', ['start_shop' => $order['start_shop']]);
        $data = [
            'car_name' => $order['car_name'],
            'car_num' => $order['carnum'],
            'order_num' => $order['ordernum'],
            'km_end' => trim($_GPC['km_end']),
            'km_start' => trim($_GPC['km_start']),
            'start_time' => trim($_GPC['start_time']),
            'end_time' => trim($_GPC['end_time']),
            'petrol_start' => trim($_GPC['petrol_start']),
            'petrol_end' => trim($_GPC['petrol_end']),
            'refund_deposit' => trim($_GPC['refund_deposit']),
            'security' => trim($_GPC['security']),
//            'refund_security' => trim($_GPC['refund_security']),
            'give_revenue' => trim($_GPC['give_revenue']),
//            'reclaim_car_cost' => trim($_GPC['reclaim_car_cost']),
            'exceed_km' => trim($_GPC['exceed_km']),
            'exceed_time' => trim($_GPC['exceed_time']),
            'driver_revenue' => trim($_GPC['driver_revenue']),
            'gasoline_subsidy_revenue' => trim($_GPC['gasoline_subsidy_revenue']),
            'peccant_revenue' => trim($_GPC['peccant_revenue']),
            'car_damage_revenue' => trim($_GPC['car_damage_revenue']),
            'repair_revenue' => trim($_GPC['repair_revenue']),
            'total_revenue' => trim($_GPC['total_revenue']),
            'callout_cost' => trim($_GPC['callout_cost']),
            'exceed_km_cost' => trim($_GPC['exceed_km_cost']),
            'intermediary_cost' => trim($_GPC['intermediary_cost']),
            'reimbursement_cost' => trim($_GPC['reimbursement_cost']),
            'driver_cost' => trim($_GPC['driver_cost']),
            'refueling_cost' => trim($_GPC['refueling_cost']),
            'refueling_subsidies_cost' => trim($_GPC['refueling_subsidies_cost']),
            'peccancy_cost' => trim($_GPC['peccancy_cost']),
            'maintenance_cost' => trim($_GPC['maintenance_cost']),
            'total_cost' => trim($_GPC['total_cost']),
            'paid_cost' => trim($_GPC['paid_cost']),
            'profit_cost' => trim($_GPC['profit_cost']),
            'difference_cost' => trim($_GPC['difference_cost']),
            'remark' => trim($_GPC['remark']),
            'uniacid' => $_W["uniacid"],
            'branch_id' => $order['start_shop'],
            'branch_name' => $branch_name,
        ];

        try {
            pdo_fetchall('START TRANSACTION');//启动一个新事务
            $order_fees = pdo_get('yzzc_sun_order_fees', ['order_id' => $_GPC['id']]);
//            if ($_GPC['total_money']){
//                pdo_update('yzzc_sun_order',['total_money' => $_GPC['total_money'] ,'prepay_money' => $_GPC['total_money']],['id' => $_GPC['id']]);
//            }
            pdo_update('yzzc_sun_order', ['is_fees' => 1], ['id' => $order_id]);
            if ($order_fees) {
                $data['updatetime'] = time();
                $res = pdo_update('yzzc_sun_order_fees', $data, ['order_id' => $_GPC['id']]);
                if (!$res) {
                    pdo_fetchall('ROLLBACK');//事务提交
                    message('提交资料失败', $this->createWebUrl('order', []), 'error');
                }
                pdo_fetchall('COMMIT');//事务提交
                message('提交资料成功', $this->createWebUrl('order', []), 'success');
            } else {
                $data['createtime'] = time();
                $data['order_id'] = $_GPC['id'];

//                //结算送车员
//                if ($order['shuttle_id']){
//                    $shuttle_update = pdo_update('yzzc_sun_shuttle_income',['order_status'=>2,'status' => 1,'income_time' => time()],['order_id'=>$order['id'],'shuttle_id'=>$order['shuttle_id']]);
//                    if (!$shuttle_update){
//                        pdo_fetchall('ROLLBACK');//事务提交
//                        message('结算商家收益失败',$this->createWebUrl('order', []),'error');
//                    }
//                }

                if ($order['distribution_id']) {

                    //结算收益
                    include_once IA_ROOT . '/addons/' . $_W['current_module']['name'] . '/inc/func/distribution.php';
                    $distribution = new Distribution();
                    $distribution->order_id = $_GPC['id'];
                    //1短租 2长租
                    $distribution->ordertype = 1;
                    $distribution->settlecommission();
                }

                if ($order['store_id']) {
                    //结算个人门店收益
                    $income_result = pdo_update('yzzc_sun_store_income', ['status' => 1, 'income_time' => time()], ['store_id' => $order['store_id'], 'order_id' => $order['id']]);
                    if (!$income_result) {
                        pdo_fetchall('ROLLBACK');//事务提交
                        message('结算商家收益失败', $this->createWebUrl('order', []), 'error');
                    }
                }

                //商家结算费用
                $branch_income = pdo_get("yzzc_sun_branch_income", ["uniacid" => $_W["uniacid"], "branch_id" => $order["start_shop"], 'order_id' => $order['id']]);
                if ($branch_income) {
                    //存在收益。直接结算
                    $income_result = pdo_update('yzzc_sun_branch_income', ['status' => 1, 'income_time' => time()], ['id' => $branch_income['id']]);
                    if (!$income_result) {
                        pdo_fetchall('ROLLBACK');//事务提交
                        message('结算商家收益失败', $this->createWebUrl('order', []), 'error');
                    }
                }
                $res = pdo_insert('yzzc_sun_order_fees', $data);
                if (!$res) {
                    pdo_fetchall('ROLLBACK');//事务提交
                    message('提交资料失败', $this->createWebUrl('order', []), 'error');
                }
                pdo_fetchall('COMMIT');//事务提交
                message('提交资料成功', $this->createWebUrl('order', []), 'success');
            }
        } catch (Exception $exception) {
            pdo_fetchall('ROLLBACK');//事务提交
            message('提交资料失败', $this->createWebUrl('order', []), 'error');
        }

    }
    $fees = pdo_get('yzzc_sun_order_fees', ['order_id' => $_GPC['id']]);
    include $this->template('web/order_fees');
    return;
}
//导出方法
/**
 * @creator Jimmy
 * @data 2018/1/05
 * @desc 数据导出到excel(csv文件)
 * @param $filename 导出的csv文件名称 如'test-'.date("Y年m月j日").'.csv'
 * @param array $tileArray 所有列名称
 * @param array $dataArray 所有列数据
 */
function exportToExcel($filename, $tileArray = array(), $dataArray = array())
{
    ini_set('memory_limit', '512M');
    ini_set('max_execution_time', 0);
    ob_end_clean();
    ob_start();
    header("Content-Type: text/csv");
    header("Content-Disposition:filename=" . $filename);
    $fp = fopen('php://output', 'w');
    fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))
    fputcsv($fp, $tileArray);
    $index = 0;
    foreach ($dataArray as $item) {
        $index++;
        fputcsv($fp, $item);
    }

    ob_flush();
    flush();
    ob_end_clean();
}

/**
 * @param $sku_id
 * @param $e_time
 * @param $s_time
 * @return true
 * 是否预订
 */
function isOrder($sku_id, $car_num, $e_time, $s_time)
{
    global $_W;
    $where = " where uniacid = " . $_W["uniacid"];
    if ($sku_id) {
        $sku = pdo_get('yzzc_sun_goods_sku', ['uniacid' => $_W['uniacid'], 'id' => $sku_id]);
        if (!$sku) {
            message('车型不存在！', '', 'error');
        }
        $cid = $sku['goods_id'];
        $where .= " and cid = '{$cid}' and (status = 2 or status = 3) and sku_id = '{$sku_id}'";
        $car_num = $sku['carnum'];
    } else {
        $where .= " and carnum = '{$car_num}'";
    }

    $order = pdo_fetch("select id from " . tablename("yzzc_sun_order") . $where);
    if (!$order) {
        $allorder = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where uniacid = " . $_W["uniacid"] . " and goods_id = {$cid} and sku_id = {$sku_id}");
        foreach ($allorder as $key => $value) {
            $start_time = $value["start_time"];
            $end_time = $value["end_time"];
            $starttime = date("Y-m-d H:i", $start_time);
            $endtime = date("Y-m-d H:i", $end_time);
            if ($s_time < $start_time && $e_time > $end_time && $start_time < $e_time && $s_time < $end_time) {
                message("您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime, '', 'error');
            } else {
                if ($s_time < $start_time && $end_time > $e_time && $start_time < $e_time && $s_time < $end_time) {
                    message("您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime, '', 'error');
                } else {
                    if ($start_time < $s_time && $e_time > $end_time && $start_time < $e_time && $s_time < $end_time) {
                        message("您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime, '', 'error');
                    } else {
                        if ($start_time < $s_time && $end_time > $e_time && $start_time < $e_time && $s_time < $end_time) {
                            message("您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime, '', 'error');
                        } else {
                        }
                    }
                }
            }
        }
        return true;
    } else {
        $allorder = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where uniacid = " . $_W["uniacid"] . " and carnum='{$car_num}'");
        foreach ($allorder as $key => $value) {
            $start_time = $value["start_time"];
            $end_time = $value["end_time"];
            $starttime = date("Y-m-d H:i", $start_time);
            $endtime = date("Y-m-d H:i", $end_time);
            if ($s_time < $start_time && $e_time > $end_time && $start_time < $e_time && $s_time < $end_time) {
                message("您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime, '', 'error');
            } else {
                if ($s_time < $start_time && $end_time > $e_time && $start_time < $e_time && $s_time < $end_time) {
                    message("您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime, '', 'error');
                } else {
                    if ($start_time < $s_time && $e_time > $end_time && $start_time < $e_time && $s_time < $end_time) {
                        message("您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime, '', 'error');
                    } else {
                        if ($start_time < $s_time && $end_time > $e_time && $start_time < $e_time && $s_time < $end_time) {
                            message("您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime, '', 'error');

                        } else {
                        }
                    }
                }
            }
        }
        return true;
    }
}

include $this->template('web/order');